//
//  ShowDataViewController.m
//  CheckIn
//
//  Created by bryan.ren on 17/01/2018.
//  Copyright © 2018 bryan. All rights reserved.
//

#import "ShowDataViewController.h"
#import "FileManage.h"

static NSString * const cellIdentify = @"DataRecordCell";

@interface ShowDataViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *recordTableView;
@property (nonatomic, copy) NSArray<NSURL *> *files;

@end

@implementation ShowDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _files = [FileManage fileArray];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSArray *)contentArray:(NSInteger)index
{
    NSURL *url = [_files objectAtIndex:index];
    if (url && ![url.absoluteString isEqualToString:@""]) {
        NSArray *contentList = [FileManage fileContent:url];
        return contentList;
    }
    return nil;
}

#pragma mark - click action

- (IBAction)closeAction:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - tableview datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_files) {
        return [_files count];
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_files && [_files count] > section) {
        NSArray *array = [self contentArray:section];
        if (array) {
            return [array count];
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    NSArray *array = [self contentArray:indexPath.section];
    if (array) {
        [cell.textLabel setText:[array objectAtIndex:indexPath.row]];
    }
    else {
        [cell.textLabel setText:@""];
    }
    return cell;
}

#pragma mark - tableview delegate

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSURL *url = [_files objectAtIndex:section];
    NSString *urlPath = url.absoluteString;
    if (url && ![urlPath isEqualToString:@""]) {
        NSInteger length = urlPath.length;
        if (length > 11) {
            return [urlPath substringWithRange:NSMakeRange(length - 11, 6)];
        }
    }
    return @"";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


@end
